﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LightSwitchApplication.Web
{
    public class DeleteRecords : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            // Get the LightSwitch serverContext
            using (var serverContext = ServerApplicationContext.CreateContext())
            {
                // Minimal security is to check for IsAuthenticated
                if (serverContext.Application.User.IsAuthenticated)
                {
                    if (context.Request.QueryString["SalesPersonId"] != null)
                    {
                        // The Salesperson was passed as a parameter
                        // Note that better security would be to check if the current user
                        // should have the ability to delete the records
                        // 'serverContext.Application.User.Name' returns the current user
                        int intSalesPersonId = Convert.ToInt32(context.Request.QueryString["SalesPersonId"]);
                        // Get the Sales records to delete
                        var result = from Sales in serverContext.DataWorkspace.ApplicationData
                                         .SalesSet.GetQuery().Execute()
                                     where Sales.SalesPerson.Id == intSalesPersonId
                                     select Sales;
                        // Loop through each record found
                        foreach (var item in result)
                        {
                            // Delete the record
                            item.Delete();
                            // Save changes
                            serverContext.DataWorkspace.ApplicationData.SaveChanges();
                        }
                        // Return a response
                        // We could return any potential errors
                        context.Response.ContentType = "text/plain";
                        context.Response.Write("complete");
                    }
                }
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}